<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.bootcss.com/flv.js/1.4.0/flv.min.js"></script>
    <style>
        *{
            box-sizing: border-box;
            margin: 0;
        }
        body{
            padding:200px;
        }
        .videoArea{
            width:700px;
            height:400px;
            border:1px solid #ccc;
        }
    </style>
</head>
<body>
   <input type="button" value="无人机">
   <br>
   <br>
   <br>
   <br>
   <span id="spanTitle">实时视频</span>
   <div class="videoArea">
    <video id="videoElement" width="100%" height='100%' controls autoplay muted></video>
   </div>
</body>
</html>
<script>
    let  flvPlayer=null
    let  fetchUrl='http://localhost:3000/flvURL'
    window.onload=()=>{
        let videoElement = document.getElementById('videoElement');
        let spanElement = document.getElementById('spanTitle');
        /* 
           target:机器,
           type:1,打开视频流
         */
        let fetchGet=function(obj){
             fetch(fetchUrl, {
             method: 'POST', // 指定请求方法为 POST
             headers: {
                 'Content-Type': 'application/json' // 指定内容类型为 JSON
             },
             body: JSON.stringify(obj)
           })
          .then(response => {
              if (response.ok) {
                  return response.json(); // 解析 JSON 响应体
              }
              throw new Error('Network response was not ok.');
          })
          .then(data =>{
            playerInit(data.flvUrl)
          })
          .catch(error => console.error('Error:', error));
            }
        let playerInit=function(flvUrl){
            playerDestroy()
            if (flvjs.isSupported()) {
                flvPlayer= flvjs.createPlayer({
                type: 'flv',
                url:flvUrl
            });
            flvPlayer.attachMediaElement(videoElement);
            flvPlayer.load();
            flvPlayer.play();
            }else{
                alert('当前浏览器不支持flvjs')
            }
    }
        let playerDestroy=function(){
        if(flvPlayer){
            flvPlayer.destroy(); // 销毁当前播放器
            flvPlayer = null; // 清空播放器引用
            videoElement.src = ''; // 清空视频源
        }
    }
        let handlerClick=function(e){
            if(e.target.localName=='input'){
                spanElement.innerText=`${e.target.defaultValue}  实时视频`
                fetchGet({target:e.target.defaultValue,type:1})
            }
        }
        window.addEventListener('click',handlerClick)
        }
    window.onbeforeunload=()=>{
        window.removeEventListener('click',handlerClick)
        playerDestroy()
    }
</script>